package com.sweetest.luffy.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sweetest.luffy.entity.DriveLine;
import com.sweetest.luffy.entity.LineRelation;
import com.sweetest.luffy.entity.User;
import com.sweetest.luffy.entity.UserLine;
import com.sweetest.luffy.page.Result;
import com.sweetest.luffy.service.IDriveLineService;
import com.sweetest.luffy.service.ILineRelationService;
import com.sweetest.luffy.service.IUserLineService;
import com.sweetest.luffy.service.IUserService;
import com.sweetest.luffy.util.GoogleMapUtil;
import com.sweetest.luffy.util.JwtUtil;
import com.sweetest.luffy.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/driver")
@Api(tags = "司机")
public class DriverController {

    @Resource
    IDriveLineService driveLineService;
    @Resource
    ILineRelationService lineRelationService;
    @Resource
    IUserLineService userLineService;
    @Resource
    IUserService userService;


    @PostMapping(value = "/saveLine")
    @ApiOperation(value = "提交行程")
    public Result<Object> advertList(HttpServletRequest request, @RequestBody DriveLine driveLine) {
        Integer id = JwtUtil.getUserId(request);
        LambdaQueryWrapper<DriveLine> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DriveLine::getUserId, id);
        queryWrapper.eq(DriveLine::getStatus, 0);
        List<DriveLine> lineList = driveLineService.list(queryWrapper);
        driveLine.setCreateDate(new Date());
        driveLine.setStatus(0);
        if (lineList.size() > 0) {
            driveLine.setId(lineList.get(0).getId());
            driveLineService.updateById(driveLine);
        } else {
            driveLineService.save(driveLine);
        }

        return Result.ok(driveLine);
    }

    @PostMapping(value = "/getUserList")
    @ApiOperation(value = "查询用户行程列表")
    public Result<List<OrderVo>> getUserList(HttpServletRequest request) {
        Integer id = JwtUtil.getUserId(request);

        LambdaQueryWrapper<DriveLine> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DriveLine::getUserId, id);
        queryWrapper.eq(DriveLine::getStatus, 0);
        DriveLine driveLine = driveLineService.getOne(queryWrapper);

        LambdaQueryWrapper<UserLine> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(UserLine::getStatus, 0);
        //七天内行程
        userQueryWrapper.between(UserLine::getStartDate, driveLine.getStartDate(), DateUtil.offsetDay(driveLine.getStartDate(), 7));
        List<UserLine> userLineList = userLineService.list(userQueryWrapper);
        PointVo vo = new PointVo();
        vo.setDLatStart(driveLine.getStartLat());
        vo.setDLngStart(driveLine.getStartLng());
        vo.setDLatEnd(driveLine.getEndLat());
        vo.setDLngEnd(driveLine.getEndLng());

        Result<List<OrderVo>> result = new Result<>();
        List<OrderVo> orderVoList = new ArrayList<>();
        for (UserLine line : userLineList) {
            //计算开始时间 秒
            int time=GoogleMapUtil.getTwoPointTime(vo);
            if(line.getStartDate().before(DateUtil.offsetSecond(driveLine.getStartDate(),time))){
                continue;
            }
            OrderVo orderVo = new OrderVo();
            BigDecimal bigDecimal = getComparePercent(vo, line);

            User user = userService.getById(line.getUserId());
            orderVo.setComparePercent(bigDecimal.intValue());
            orderVo.setEndAddress(line.getEndAddress());
            orderVo.setStartAddress(line.getStartAddress());
            orderVo.setFirstName(user.getFirstName());
            orderVo.setLastName(user.getLastName());
            orderVo.setPhone(user.getPhone());
            orderVo.setStartDate(line.getStartDate());
            orderVo.setTravelNum(line.getTravelNum());
            orderVo.setUserLineId(line.getId());

            orderVoList.add(orderVo);

        }
        //过滤1.5倍
        orderVoList.stream().filter(e -> new BigDecimal(e.getComparePercent()).compareTo(new BigDecimal(50D)) == 1).collect(Collectors.toList());
        //排序
        orderVoList = orderVoList.stream().sorted((s2, s1) -> s1.getComparePercent().compareTo(s2.getComparePercent())).collect(Collectors.toList());

        result.setData(orderVoList);
        return result;
    }

    private BigDecimal getComparePercent(PointVo vo, UserLine line) {
        vo.setULatEnd(line.getEndLat());
        vo.setULngEnd(line.getEndLng());
        vo.setULatStart(line.getStartLat());
        vo.setULngStart(line.getEndLng());

        double take = GoogleMapUtil.getFourPointDistance(vo);
        double along = GoogleMapUtil.getTwoPointDistance(vo);
        System.out.println("全部行程----------------:"+take);
        System.out.println("司机行程----------------:"+along);
        return new BigDecimal(along * 100).divide(new BigDecimal(take), 4, RoundingMode.HALF_UP);
    }

    @PostMapping(value = "/take")
    @ApiOperation(value = "接单")
    public Result<Object> advertList(HttpServletRequest request, @RequestBody LineRelation lineRelation) {

        if (CommonUtil.checkNull(lineRelation.getDriverLineId(), lineRelation.getUserLineId())) {
            return Result.ok(10400);
        }
        Integer id = JwtUtil.getUserId(request);
        DriveLine driveLine = driveLineService.getById(lineRelation.getDriverLineId());
        UserLine userLine = userLineService.getById(lineRelation.getUserLineId());
        if (!id.equals(driveLine.getUserId()) || 0 != driveLine.getStatus()) {
            return Result.ok(10400);
        }
        LambdaQueryWrapper<LineRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LineRelation::getDriverLineId, lineRelation.getDriverLineId());
        queryWrapper.eq(LineRelation::getUserLineId, lineRelation.getUserLineId());
        int count = lineRelationService.count(queryWrapper);
        if (count > 0) {
            return Result.ok(10400);
        }
        userLine.setStatus(3);
        userLineService.updateById(userLine);
        lineRelation.setUserId(userLine.getUserId());
        lineRelation.setDriverId(driveLine.getUserId());
        lineRelation.setCreateDate(new Date());
        lineRelationService.save(lineRelation);
        return Result.ok(LineRelation2OrderVo(lineRelation));
    }

    @PostMapping(value = "/accept")
    @ApiOperation(value = "完成  2乘客上车 3完成")
    public Result<Object> sure(HttpServletRequest request, @RequestBody AcceptVo acceptVo) {
//        DriveLine userLine = driveLineService.getById(acceptVo.getId());
        LineRelation lineRelation = lineRelationService.getById(acceptVo.getId());
        UserLine userLine = userLineService.getById(lineRelation.getUserLineId());
        userLine.setStatus(acceptVo.getStatus());
        userLineService.updateById(userLine);
        DriveLine driveLine = driveLineService.getById(lineRelation.getDriverLineId());
        driveLine.setStatus(acceptVo.getStatus());
        driveLineService.updateById(driveLine);
        return Result.ok(userLine);
    }


    @GetMapping(value = "/getOrderList")
    @ApiOperation(value = "订单列表")
    public Result<List<OrderVo>> getOrderList(HttpServletRequest request) {
        Result<List<OrderVo>> result = new Result<>();
        Integer id = JwtUtil.getUserId(request);
        LambdaQueryWrapper<LineRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LineRelation::getDriverId, id);
        List<LineRelation> lineRelations = lineRelationService.list(queryWrapper);
        List<OrderVo> list = new ArrayList<>();
        for (LineRelation lineRelation : lineRelations) {
            list.add(LineRelation2OrderVo(lineRelation));
        }
        result.setData(list);
        return result;
    }

    private OrderVo LineRelation2OrderVo(LineRelation lineRelation) {

        OrderVo vo = new OrderVo();
        User user = userService.getById(lineRelation.getUserId());
        vo.setCarType(user.getCarType());
        BeanUtil.copyProperties(user, vo);
        UserLine userLine = userLineService.getById(lineRelation.getUserLineId());
        BeanUtil.copyProperties(userLine, vo);

        DriveLine driveLine = driveLineService.getById(lineRelation.getDriverLineId());

        PointVo pointVo = new PointVo();
        pointVo.setULngStart(userLine.getStartLng());
        pointVo.setULatStart(userLine.getStartLat());
        pointVo.setULngEnd(userLine.getEndLng());
        pointVo.setULatEnd(userLine.getEndLat());

        pointVo.setDLngEnd(driveLine.getEndLng());
        pointVo.setDLatEnd(driveLine.getEndLat());
        pointVo.setDLngStart(driveLine.getStartLng());
        pointVo.setDLatStart(driveLine.getStartLat());

        vo.setId(lineRelation.getId());
        vo.setPointVo(pointVo);
        return vo;
    }

    @GetMapping(value = "/getMaps")
    @ApiOperation(value = "获取maps")
    public Result<List<POI>> getMaps() {
        Result<List<POI>> result = new Result<>();
        result.setData(Maps.pointsOfInterest);
        return result;
    }

}
